package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.*;
import com.mainbo.modular.system.model.PtConfig;
import com.mainbo.modular.system.model.meta.ConfigConstants;
import com.mainbo.modular.system.model.meta.ConfigConstants.MetaCodeTree;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.SchoolYearVo;
import com.mainbo.modular.system.service.IPtConfigService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author xww
 * @Description //TODO
 * @Date 2020/3/10   14:42
 **/
@Controller
@RequestMapping("/ptConfig")
public class PtConfigController extends BaseController {
    private static final Logger logger= LoggerFactory.getLogger(PtConfigController.class);

    private final  String PREFIX="/system/dic/";
    @Resource
    private IPtConfigService configService;
    @Resource
    private JmsService jmsService;

    /**
     * 删除元数据
     *
     * @param id
     *          元数据id
     */
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Result deleteDic(@PathVariable("id") Integer id) {
        Result result = new Result();
        try {
            PtConfig config = configService.selectById(id);
            if (config != null) {
                ConfigConstants.MetaCodeTree tree = ConfigConstants.MetaCodeTree.getTree(config.getCode());
                configService.deleteById(id);
                if (tree != null && tree.isHasChild()) { // 有子级，同时删除子级
                    EntityWrapper<PtConfig> wrapper = new EntityWrapper<>();
                    wrapper.eq("phase",id);
                    List<PtConfig> cfgList = configService.selectList(wrapper);
                    for (PtConfig cf : cfgList) {
                        configService.deleteById(cf.getId());
                    }
                }
                // LoggerUtils.deleteLogger(LoggerModule.META, "删除元数据成功，id : {}", id);
                result.setCode(Result.SUCCESS);
                result.setMsg("删除成功");
                if (config.getCode().equals(ConfigConstants.SCHOOLYEAR_CODE)){
                    SchoolYearVo schoolYearVo=new SchoolYearVo();
                    schoolYearVo.setId(config.getId());
                    schoolYearVo.setCrtDttm(config.getCrtDttm());
                    jmsService.sendMessage(new SchoolYearMessage(MessageTypes.SCHOOLYEAR_DELETE.name(),schoolYearVo));
                }else if (config.getCode().equals(ConfigConstants.TERM_CODE)){
                    TermVo termVo=new TermVo();
                    termVo.setId(config.getId());
                    jmsService.sendMessage(new TermMessage(MessageTypes.TERM_DELETE.name(),termVo));
                }else {
                    MetaMessage msg = new MetaMessage();
                    msg.setContent(id);
                    MetaVo vo = new MetaVo();
                    BeanUtils.copyProperties(config, vo);
                    msg.setVo(vo);
                    msg.setMessageType(MessageTypes.META_DELETE.name());
                    jmsService.sendMessage(msg);
                }
            }
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("删除失败");
            logger.error("删除元数据失败", e);
        }
        return result;
    }
    /**
     * 首页
     *
     * @param codeName
     *          code名称
     */
    @RequestMapping("/{codeName}/index")
    public String index(@PathVariable("codeName") String codeName, @RequestParam(value = "orgId",required = false) String orgId, Model m) {
        m.addAttribute("orgId", orgId);
        m.addAttribute("code",codeName);
        return PREFIX+"dic_index.html";
    }

    @RequestMapping("/findList")
    @ResponseBody
    public Object findList(@RequestParam("code")String code,@RequestParam(value = "orgId",required = false) String orgId){
        List<Meta> metas;
         code= MetaCodeTree.valueOf(code).getCode();
        if (StringUtils.isNotBlank(orgId)){
           metas= MetaUtils.listMeta(code,orgId);
        }else {
            metas=   MetaUtils.listMeta(code);
        }
        return metas;
    }

    @RequestMapping("/toAdd")
    public  String toAdd(@RequestParam("code")String code,@RequestParam("orgId")String orgId,Model model){
        model.addAttribute("code", ConfigConstants.MetaCodeTree.valueOf(code));
        model.addAttribute("orgId",orgId);
        return PREFIX+"dic_add.html";
    }
    @RequestMapping("/toUpdate")
    public  String toUpdate(@RequestParam("id")String id,Model model){
        Meta meta=MetaUtils.getMeta(Integer.valueOf(id));
        model.addAttribute("meta",meta);
        return PREFIX+"dic_edit.html";
    }
    /**
     * 保存元数据
     *
     * @param model
     *          Config
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public Result saveDic(PtConfig model) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        if (model.getId() == null) {
            if (isNameExist(model.getName(), model.getCode())) {
                result.setCode(Result.FAIL);
                result.setMsg("配置名称重复");
                return result;
            }
            MetaCodeTree tree = ConfigConstants.MetaCodeTree.getTree(model.getCode());
            if (tree != null && tree.isDic()) {
                PtConfig old = configService.selectById(Integer.valueOf(model.getValue()));
                if (old != null) {
                    result.setCode(Result.FAIL);
                    result.setMsg("配置id重复");
                    return result;
                }
            }

            model.setType(ConfigConstants.SYS_TYPE);
            model.setEnable(1);
           configService.insert(model);

            if (tree != null && !tree.isDic() && null == model.getValue()) {
                model.setValue(String.valueOf(model.getId()));
                configService.updateById(model);
            } else if (tree != null && tree.isDic()) {
                PtConfig cm = new PtConfig();
                cm.setId(model.getId());
               // cm.addCustomCulomn(" id = \"" + model.getValue() + "\"");
                configService.updateById(cm);
                model.setId(Integer.valueOf(model.getValue()));
            }

            MetaVo vo = new MetaVo();
            BeanUtils.copyProperties(model, vo);
            MetaMessage message = new MetaMessage(MessageTypes.META_ADD.name(), vo);
            jmsService.sendMessage(message);
//            LoggerUtils.insertLogger(LoggerModule.META, "保存元数据配置成功：code: {} ,name:{}, value : {}", model.getCode(),
//                    model.getName(), model.getValue());
        } else {
            MetaCodeTree tree = ConfigConstants.MetaCodeTree.getTree(model.getCode());
            configService.updateById(model);

            if (tree != null && !tree.isNeedValue()) {
                MetaVo vo = new MetaVo();
                BeanUtils.copyProperties(model, vo);
                MetaMessage message = new MetaMessage(MessageTypes.META_UPDATE.name(), vo);
                jmsService.sendMessage(message);
            }

//            LoggerUtils.updateLogger(LoggerModule.META, "更新元数据成功：code: {} ,name:{}, value : {}", model.getCode(),
//                    model.getName(), model.getValue());
        }
        result.setMsg("新增成功!");
        return result;
    }
    protected boolean isNameExist(String name, String code) {
        EntityWrapper<PtConfig> config = new EntityWrapper<>();
        config.eq("type",ConfigConstants.SYS_TYPE);
        config.eq("code",code);
        config.eq("name",name);
        return null != configService.selectOne(config);
    }


}
